package middlewares

import (
	"douyin/models"
	"douyin/utils/pack"
	"douyin/utils/pkg/jwt"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// JWTAuthMiddleware 基于JWT的认证中间件
func JWTAuthMiddleware() func(c *gin.Context) {
	return func(c *gin.Context) {
		//1.获取token
		token := c.Query("token") //从url获取
		if token == "" {
			token = c.PostForm("token") //从form获取
		}
		//JWT 中间件修改
		if token == "" {
			zap.L().Error("UnLogin user")
			c.Set(pack.CtxUserIDKey, int64(0))
			c.Next()
		} else {
			//2.解析token,鉴权
			MyClaims, err := jwt.ParseToken(token)
			if err != nil {
				zap.L().Error("middlewares.JWTAuthMiddleware Parse Token failed!", zap.Error(err))
				pack.ResponseError(c, models.CodeInvalidToken)
				c.Abort()
				return
			}
			//3.将当前请求的userID信息保存到请求的上下文c上
			c.Set(pack.CtxUserIDKey, MyClaims.UserID) //此处userID为登录用户userid
			c.Next()                                  // 后续的处理请求的函数中 可以用过c.Get(CtxUserIDKey) 来获取当前请求的用户信息
		}
	}
}
